﻿<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="../../Scripts/jquery-1.11.0.min.js" type="text/javascript"></script>
    <script language="JavaScript" src="../../Comm/JScript.js" type="text/javascript"></script>
    <script type="text/javascript" src="../../Scripts/QueryString.js"></script>
    <script type="text/javascript" src="../../Scripts/config.js"></script>
    <script type="text/javascript" src="../../Comm/Gener.js"></script>

    <script src="../../Scripts/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
    <link href="../../Scripts/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

    <link href="../../Scripts/bootstrap/css/font-awesome.css" rel="stylesheet" type="text/css" />

    <script src="../../Scripts/bootstrap/bootstrap-table/src/bootstrap-table.js" type="text/javascript"></script>
    <link href="../../Scripts/bootstrap/bootstrap-table/src/bootstrap-table.css" rel="stylesheet" type="text/css" />
    <script src="../../Scripts/bootstrap/bootstrap-table/src/locale/bootstrap-table-zh-CN.js" type="text/javascript"></script>

    <script src="../../Scripts/bootstrap/bootstrap-treeview/src/js/bootstrap-treeview.js" type="text/javascript"></script>
    <link href="../../Scripts/bootstrap/bootstrap-treeview/src/css/bootstrap-treeview.css" rel="stylesheet" type="text/css" />
    <!-- 引入用户要重写的公共js -->
    <script src="../../../DataUser/JSLibData/CCFormRef.js" type="text/javascript"></script>

    <style type="text/css">
        .row-margin-top {
            margin-top: 20px;
        }

        .search-margin {
            margin-top: 15px;
        }
    </style>

    <script type="text/javascript">
        function loadViewGrid(json) {
            if ($.isArray(json)) {
                $('#viewGrid').bootstrapTable("load", json);
            }
        }
        function addSelectedData(globalSelectedRows, selectedRows) {
            if (!$.isArray(globalSelectedRows) || !$.isArray(selectedRows)) {
                return;
            }
            $.each(selectedRows, function (i, o) {
                var sel = $.grep(globalSelectedRows, function (obj) {
                    return obj.No == o.No;
                });
                if (sel.length == 0) {
                    SaveVal(FK_MapData, AttrOfOper, oid, o.No, o.Name);
                    globalSelectedRows.push(o);
                }
            });
        }
        function removeSelectedData(globalSelectedRows, selectedRows) {
            if (!$.isArray(globalSelectedRows) || !$.isArray(selectedRows)) {
                return;
            }
            $.each(selectedRows, function (i, o) {
                for (var index = 0; index < globalSelectedRows.length; index++) {
                    if (o.No == globalSelectedRows[index].No) {
                        Delete(AttrOfOper, oid, o.No);
                        globalSelectedRows.splice(index, 1);
                        break;
                    }
                }
            });
        }
        function removeAllSelectedData() {
            var globalSelectedRows = selectedRows;
            if (!$.isArray(globalSelectedRows) || !$.isArray(selectedRows)) {
                return;
            }
            for (var index = 0; index < globalSelectedRows.length; index++) {
                Delete(AttrOfOper, oid, globalSelectedRows[index].No);
            }
            selectedRows = [];
        }
        function loadSelectGrid(dbSrc, selectedRows, dbType) {

            //获得json.
            var json = DBAccess.RunDBSrc(dbSrc, dbType);

            //  alert(JSON.stringify(json));

            if (!$.isArray(json) || json.length == 0) {
                $('#selectGrid').bootstrapTable("load", json);
                return;
            }

            // 绑定内容列表.
            $('#selectGrid').bootstrapTable("hideAllColumns");
            if (selectType != "0") {
                $('#selectGrid').bootstrapTable("showColumn", "_checkbox");
            }

            $.each(json[0], function (n, o) {
                var column = $.grep(searchTableColumns, function (val) {
                    return val.field == n;
                });
                if (column.length > 0) {
                    $('#selectGrid').bootstrapTable("showColumn", n);
                }
            });

            if ($.isArray(selectedRows)) {
                $.each(json, function (i, o) {
                    var sel = $.grep(selectedRows, function (obj) {
                        return o.No == obj.No;
                    });
                    if (sel.length > 0) {
                        o.checked = true;
                    }
                });
            }
            $('#selectGrid').bootstrapTable("load", json);
        }

        function findChildren(jsonArray, parentNo, lazyLoad) {
            var appendToTree = function (treeToAppend, o) {
                $.each(treeToAppend, function (i, child) {
                    if (o.id == child.ParentNo)
                        o.nodes.push({
                            "id": child.No,
                            "text": child.Name,
                            "nodes": []
                        });
                });

                $.each(o.nodes, function (i, o) {
                    appendToTree(jsonArray, o);
                });

            };

            var jsonTree = [];
            var jsonchildTree = [];
            if ($.isArray(jsonArray) && typeof parentNo !== "undefined") {
                //如果parentNo不为0，则增加parentNo的部门数据
                if (parentNo != 0) {
                    $.each(jsonArray, function (i, item) {
                        if (item.No == parentNo) {
                            jsonTree.push({
                                "id": parentNo,
                                "text": item.Name,
                                "nodes": []
                            });
                            return;
                        }
                    });    
                }
                
                
                $.each(jsonArray, function (i, o) {
                    if (o.ParentNo == parentNo) {
                        jsonchildTree.push(o);
                        jsonTree.push({
                            "id": o.No,
                            "text": o.Name,
                            "nodes": []
                        });
                    }
                });

                $.each(jsonTree, function (i, o) {
                    appendToTree(jsonArray, o);
                });

            }
            function _(treeArray) {
                $.each(treeArray, function (i, o) {
                    if ($.isArray(o.nodes)) {
                        if (o.nodes.length == 0) {
                           // o.nodes = undefined;
                        } else {
                            _(o.nodes);
                        }
                    }
                });
            }
            _(jsonTree);
            return jsonTree;
        }
        function loadTree(treeUrl, treeClickUrl, rootNo, global) {

           
            var json = DBAccess.RunDBSrc(treeUrl, global.dbType); //执行url返回json.

           
            var jsonTree = findChildren(json, rootNo);

            $('#tree').treeview({
                data: jsonTree,         // 数据源
                showCheckbox: false,   //是否显示复选框
                highlightSelected: true,    //是否高亮选中
                //nodeIcon: 'glyphicon glyphicon-user',    //节点上的图标
                nodeIcon: 'glyphicon',
                emptyIcon: '',    //没有子节点的节点图标
                multiSelect: false,    //多选
                onNodeChecked: function (event, data) {
                    //alert(data.id);
                },
                onNodeSelected: function (event, data) {
                    var myurl = replaceAll(treeClickUrl, "@Key", data.id);
                    myurl = replaceAll(myurl, "~", "'");
                    loadSelectGrid(myurl, global.selectedRows, global.dbType);

                },
                onNodeExpanded: function (event, data) {
                    if (global.TreeUrl.indexOf("@Key") != -1) {
                        var url = global.TreeUrl.replace("@Key", data.id);
                        var json = DBAccess.RunDBSrc(url, global.dbType);
                        var jsonTree = findChildren(json, data.id, global.lazyLoad);
                        $("#tree").treeview("deleteChildrenNode", data.nodeId);	//删除当前节点下的所有子节点

                        $("#tree").treeview("addNode", [data.nodeId, { node: jsonTree, silent: true }]);
                       
                       
                    }
                }
            });
        }
        function isLegalName(name) {
            if (!name) {
                return false;
            }
            return name.match(/^[a-zA-Z\$_][a-zA-Z\d\$_]*$/);
        }
        $(function () {

            var mypk = GetQueryString("MyPK");
            var mapExt = new Entity("BP.Sys.MapExt", mypk);

            var webUser = new WebUser();

            // AtPara
            var title = mapExt.GetPara("Title");
            $("#title").text(title); //设置标题.

            var tip = mapExt.GetPara("SearchTip");
            $("#TB_Key").attr("placeholder", tip); //设置查询提示.

            //跟节点编号.
            var rootNo = mapExt.Doc;
            if (rootNo == "@WebUser.FK_Dept") {
                rootNo = webUser.FK_Dept;
            }
            if (rootNo == "@WebUser.OrgNo") {
                rootNo = webUser.OrgNo;
            }
            if (rootNo == null || rootNo == undefined ) {
                rootNo="0"
            }

            // global
            var global = window;
            global.selectedRows = [];

            //设置变量.
            global.FK_MapData = mapExt.FK_MapData;
            global.AttrOfOper = mapExt.AttrOfOper;
            global.oid = GetQueryString("OID");
            global.dbType = mapExt.DBType;
            

            var searchUrl = mapExt.Tag1;    //查询
            var treeUrl = mapExt.Tag2;      //初始化树
            var treeClickUrl = mapExt.Tag3; //树选择.

            var atParas = GetQueryString("AtParas");
            var treeUrl = mapExt.Tag2;
            var treeTag1 = mapExt.Tag1;
            if (atParas.indexOf('@') == 0) {
                var paras = atParas.split('@');
                for (i = 0, len = paras.length; i < len; i++) {
                    var key = paras[i];
                    if (key == "" || key == null) {
                        continue;
                    }
                    var attrKeyOfEn = key.split('=')[0];
                    var val = key.split('=')[1];
                    searchUrl = searchUrl.replace("@" + attrKeyOfEn, val);
                    treeUrl = treeUrl.replace("@" + attrKeyOfEn, val);
                    treeClickUrl = treeClickUrl.replace("@" + attrKeyOfEn, val);
                }
            }
            global.TreeUrl = mapExt.Tag2;
            treeUrl = treeUrl.replace("@Key", rootNo);
            if (searchUrl == "" || treeUrl == "" || treeClickUrl == "") {
                alert('配置错误:查询数据源，初始化树的数据源，点击树节点返回数据的数据源，必须都不能为空。');
                return;
            }

            global.selectType = mapExt.GetPara("SelectType");

            global.searchTableColumns = [];
            if (selectType != "0") {
                global.searchTableColumns.push({
                    field: "_checkbox",
                    checkbox: true,
                    formatter: function (value, row, index) {
                        if (row.checked) {
                            return {
                                "checked": true
                            };
                        }
                    }
                });
            }

            //显示列的中文名称.
            if (typeof mapExt.Tag == "string" && mapExt.Tag != null && mapExt.Tag != "") {

                $.each(mapExt.Tag.split(","), function (i, o) {
                    var exp = o.split("=");
                    var field;
                    var title;
                    if (exp.length == 1) {
                        field = title = exp[0];
                    } else if (exp.length == 2) {
                        field = exp[0];
                        title = exp[1];
                    }
                    if (!isLegalName(field)) {
                        return true;
                    }
                    searchTableColumns.push({
                        field: field,
                        title: title
                    });
                });
            } else {
                // by default
                searchTableColumns.push({
                    field: 'No',
                    title: '编号'
                });
                searchTableColumns.push({
                    field: 'Name',
                    title: '名称'
                });
            }

            // search
            $("#TB_Key").on("keyup", function () {

                var key = replaceAll($(this).val(), "'", "");
                var mySrc = replaceAll(searchUrl, "@Key", key);
                mySrc = replaceAll(mySrc, "~", "'");
                loadSelectGrid(mySrc, global.selectedRows, global.dbType);

            });

            // tree
            loadTree(treeUrl, treeClickUrl, rootNo, global);

            // grid1
            var options = {
                striped: true,
                cache: false,
                sortOrder: "asc",
                strictSearch: true,
                minimumCountColumns: 2,
                clickToSelect: true,
                sortable: false,
                cardView: false,
                detailView: false,
                height: $(document).height() / 3,
                uniqueId: "No",
                columns: searchTableColumns
            };
            if (selectType == "0") {
                options.onClickRow = function (row, element) {
                    removeAllSelectedData();
                    addSelectedData(global.selectedRows, [row]);
                    loadViewGrid(global.selectedRows);
                }
            } else {
                options.onCheck = function (row, element) {
                    addSelectedData(global.selectedRows, [row]);
                    loadViewGrid(global.selectedRows);
                };
                options.onUncheck = function (row, element) {
                    removeSelectedData(global.selectedRows, [row]);
                    loadViewGrid(global.selectedRows);
                };
                options.onCheckAll = function (rows) {
                    addSelectedData(global.selectedRows, rows);
                    loadViewGrid(global.selectedRows);
                };
                options.onUncheckAll = function (rows) {
                    removeSelectedData(global.selectedRows, rows);
                    loadViewGrid(global.selectedRows);
                };
            }
            $('#selectGrid').bootstrapTable(options);

            // grid2
            $('#viewGrid').bootstrapTable({
                striped: true,
                cache: false,
                sortOrder: "asc",
                strictSearch: true,
                minimumCountColumns: 2,
                clickToSelect: true,
                sortable: false,
                cardView: false,
                detailView: false,
                height: $(document).height() / 3,
                uniqueId: "No",
                columns: [{
                    field: 'No',
                    title: '编号'
                }, {
                    field: 'Name',
                    title: '名称'
                }, {
                    title: '操作', formatter: function (value, row, index) {
                        return '<a class="btn btn-danger" href="#" onclick="removeRecord(\'' + row.No + '\')">X</a>';
                    }
                }]
            });

            // 初始化加载
            var frmEleDBs = new Entities("BP.Sys.FrmEleDBs");
            frmEleDBs.Retrieve("FK_MapData", FK_MapData, "EleID", AttrOfOper, "RefPKVal", oid);
            $.each(frmEleDBs, function (i, o) {
                global.selectedRows.push({
                    "No": o.Tag1,
                    "Name": o.Tag2
                });
            });
            loadViewGrid(global.selectedRows);
        });
        function removeRecord(No) {
            $("#selectGrid").bootstrapTable("uncheckBy", {
                field: "No",
                values: [No]
            });
            //
            Delete(AttrOfOper, oid, No);
            $('#viewGrid').bootstrapTable("remove", {
                field: "No",
                values: [No]
            });
        }

        //删除数据.
        function Delete(keyOfEn, oid, No) {
            var frmEleDB = new Entity("BP.Sys.FrmEleDB");
            frmEleDB.MyPK = keyOfEn + "_" + oid + "_" + No;
            frmEleDB.Delete();
        }
        //设置值.
        function SaveVal(fk_mapdata, keyOfEn, oid, val1, val2) {
            var frmEleDB = new Entity("BP.Sys.FrmEleDB");
            frmEleDB.MyPK = keyOfEn + "_" + oid + "_" + val1;
            frmEleDB.FK_MapData = fk_mapdata;
            frmEleDB.EleID = keyOfEn;
            frmEleDB.RefPKVal = oid;
            frmEleDB.Tag1 = val1;
            frmEleDB.Tag2 = val2;
            if (frmEleDB.Update() == 0) {
                frmEleDB.Insert();
            }
        }
    </script>
</head>
	<body style="overflow-y:hidden">
        <div class="container-fluid" style="overflow:hidden">
	        <div class="row">
		        <div class="col-md-12">
					<div class="row">
						<div class="col-md-3 col-sm-3">
							<h3 class="text-center" id="title"></h3>
						</div>
						<div class="col-md-9 col-sm-9">
							<div class="pull-center search search-margin">
								<input class="form-control" type="text" placeholder="" id="TB_Key">
							</div>
						</div>
					</div>
		        </div>
	        </div>
	        <div class="row row-margin-top">
		        <div class="col-md-4 col-sm-4" style="height:500px">
                    <div id="tree" style="overflow-y:auto;height:100%"></div>
		        </div>
		        <div class="col-md-8 col-sm-8">
					<div class="row">
						<div class="col-md-12">
							<table id="selectGrid"></table>
						</div>
					</div>
					<div class="row row-margin-top">
						<div class="col-md-12">
							<table id="viewGrid"></table>
						</div>
					</div>
		        </div>
	        </div>
        </div>
	</body>
</html>